package com.techstar.common.jackson;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.deser.JodaDateDeserializerBase;
import com.techstar.api.pojo.bus.RealtimeTraffic;

public class RealtimeTrafficDeserializer extends JodaDateDeserializerBase<DateTime>{
		private static final long serialVersionUID = 1L;

		public RealtimeTrafficDeserializer() {
	        this(DateTime.class, FormatConfig.DEFAULT_LOCAL_DATEONLY_FORMAT);
	    }

	    protected RealtimeTrafficDeserializer(Class<?> type, JacksonJodaDateFormat format) {
	    	super(type, format);
	    }
	    @Override
	    public JodaDateDeserializerBase<?> withFormat(JacksonJodaDateFormat jacksonJodaDateFormat) {
	        return new com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer(DateTime.class, jacksonJodaDateFormat);
	    }
		@Override
		public DateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException{
			RealtimeTraffic d = (RealtimeTraffic)ctxt.getParser().getParsingContext().getCurrentValue();
			if (StringUtils.isBlank(jp.getText())||"null".equals(jp.getText().toLowerCase())) {
				return (DateTime) ctxt.handleUnexpectedToken(this.handledType(), jp.getCurrentToken(), jp, "expected String, Number or JSON Array", new Object[0]);
			}else {
				DateTime createTime = DateTime.parse(jp.getText().trim(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
				d.setExecDate(createTime.toString("yyyy-MM-dd"));
				return createTime;
			}
		}

	}